/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.security.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;

import com.iiifi.kite.core.exception.ServiceException;
import com.iiifi.kite.core.model.KiteAccount;
import com.iiifi.kite.core.result.Result;
import com.iiifi.kite.security.model.KiteAuthForm;
import com.iiifi.kite.security.model.KiteRestTemplate;
import com.iiifi.kite.security.properties.KiteSecurityProperties;
import com.iiifi.kite.security.service.KiteSecurityService;
import com.iiifi.kite.security.utils.KiteUtils;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * KiteSecurityService默认实现
 *
 * @author kite@iiifi.com 花朝
 */
@Slf4j
@AllArgsConstructor
public class KiteSecurityServiceDefaultImpl implements KiteSecurityService {

    private final KiteSecurityProperties properties;

    private final KiteRestTemplate kiteRestTemplate;

    @Override
    public KiteAccount auth(KiteAuthForm kiteAuthForm) {
        // 从认证中心获取用户信息
        String requestUrl = properties.getApiAddress() + "/v1-0/auth/starter-auth";
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<KiteAuthForm> httpEntity = new HttpEntity<>(kiteAuthForm, headers);
        ParameterizedTypeReference<Result<KiteAccount>> responseType =
                new ParameterizedTypeReference<Result<KiteAccount>>() {};
        ResponseEntity<Result<KiteAccount>> responseEntity =
                kiteRestTemplate.exchange(requestUrl, HttpMethod.POST, httpEntity, responseType);
        Result<KiteAccount> result = responseEntity.getBody();
        assert result != null;
        if (!result.isSuccess()) {
            log.warn("kite-security 鉴权失败 ==> code:{},message:{}", result.getCode(), result.getMsg());
            throw new ServiceException(result);
        }
        return result.getData();
    }

    @Override
    public KiteAccount getAccount(String token, String deviceId) {
        // 从认证中心查询用户信息
        String requestUrl = properties.getApiAddress() + "/v1-0/auth/accounts";
        Map<String, Object> map = new HashMap<>(16);
        map.put("token", token);
        map.put("deviceId", deviceId);
        map.put("sdkVersion", KiteUtils.SDK_VERSION);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map);
        ParameterizedTypeReference<Result<KiteAccount>> responseType =
                new ParameterizedTypeReference<Result<KiteAccount>>() {};
        ResponseEntity<Result<KiteAccount>> responseEntity =
                kiteRestTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, responseType);
        Result<KiteAccount> result = responseEntity.getBody();
        assert result != null;
        if (!result.isSuccess()) {
            log.warn("kite-security 查询账号信息失败 ==> code:{},message:{}", result.getCode(), result.getMsg());
            throw new ServiceException(result);
        }
        return result.getData();
    }
}
